package day8;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;

/**
 * @author oldliu
 * @since 1.0
 */
public class ValidPicture {
    public static void main(String[] args) {
        //String fileName = "D:\\Documents\\桌面\\阶段总结.jpg";
        String fileName = "D:\\Documents\\图片和资料\\1111.png";
        //后缀
        File f = new File(fileName);
        if(f.isFile()==false){
            System.out.println("闪");
            return;//是文件夹
        }
        String name=f.getName();
        String suffix=name.substring(name.lastIndexOf('.')+1).toUpperCase();
        System.out.println("后缀:"+suffix);
        int []ar=new int[8];//byte[8] -1
        try {
            FileInputStream fin=new FileInputStream(f);
            for(int i=0;i<ar.length;i++){
                ar[i]=fin.read();
            }
            fin.close();
        } catch (java.io.IOException e) {
            System.out.println("读取发生错误");
            e.printStackTrace();
            return;
        }
        //switch
        switch (suffix){
            case "JPG":
            case "JPEG":
                if(ar[0]==0xff &&ar[1]==0xd8){
                    System.out.println("合法的jpg文件");
                }else{
                    System.out.println("非法的jpg文件");
                }
                break;
            case "GIF":
                int []a2={0x47,0x49,0x46,0x38,0x39,0x61};
                int []a3={0x47,0x49,0x46,0x38,0x37,0x61};
                int[] a0 = Arrays.copyOf(ar, 6);
                if(Arrays.equals(a2,a0)||Arrays.equals(a3,a0)){
                    System.out.println("合法的gif文件");
                }else{
                    System.out.println("非法的gif文件");
                }
                break;
            case "PNG":
                if(Arrays.equals(ar,new int[]{0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A})){
                    System.out.println("合法的png文件");
                }else{
                    System.out.println("非法的png文件");
                }
                break;
            case "BMP":
                if(ar[0]==0x42 &&ar[1]==0x4d){
                    System.out.println("合法的bmp文件");
                }else{
                    System.out.println("非法的bmp文件");
                }
                break;
        }

    }
}
